

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using JTC.MiniCommerce.Core;
using JTC.MiniCommerce.Localization;
using JTC.MiniCommerce.Store;
using SubSonic;

namespace JTC.MiniCommerce.Web.admin {
  public partial class categoryedit : System.Web.UI.Page {

    #region Member Variables

    DataSet ds;

    #endregion

    #region Page Events

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e) {
      try {
        SetCategoryEditProperties();
        btnDelete.Visible = false;
        //http://aspalliance.com/822
        if(!Page.IsPostBack) {
          GetCategoryDataSet();
          LoadTreeView(ds);
          LoadParentCategoryDropDown(ds);
        }
      }
      catch(Exception ex) {
        Logger.Error(typeof(categoryedit).Name + ".Page_Load", ex);
        Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    /// <summary>
    /// Handles the Selected event of the Category control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void Category_Selected(object sender, EventArgs e) {
      try {
        int categoryId = 0;
        int.TryParse(tvCategory.SelectedNode.Value, out categoryId);
        if(categoryId > 0) {
          Category category = new Category(categoryId);
          lblCategoryId.Text = category.CategoryId.ToString();
          ddlParentCategory.SelectedValue = category.ParentId.ToString();
          txtName.Text = category.Name;
          txtImageFile.Text = category.ImageFile;
          txtDescription.Text = category.Description;
          //if no kids, then set the delete button
          CategoryCollection categoryCollection = new CategoryCollection().Where(Category.Columns.ParentId, Comparison.Equals, categoryId).Load();
          if(categoryCollection.Count == 0) {
            btnDelete.Visible = true;
          }
        }
      }
      catch(Exception ex) {
        Logger.Error(typeof(categoryedit).Name + ".Category_Selected", ex);
        Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    /// <summary>
    /// Handles the Click event of the btnDelete control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnDelete_Click(object sender, EventArgs e) {
      try {
        int categoryId = 0;
        int.TryParse(lblCategoryId.Text, out categoryId);
        if(categoryId > 0) {
          Category.Delete(categoryId);
          GetCategoryDataSet();
          LoadTreeView(ds);
          LoadParentCategoryDropDown(ds);
          btnDelete.Visible = false;
          Reset();
          Master.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblProductCategoryDeleted"));
        }
      }
      catch(Exception ex) {
        Logger.Error(typeof(categoryedit).Name + ".btnDelete_Click", ex);
        Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    /// <summary>
    /// Handles the Click event of the btnReset control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnReset_Click(object sender, EventArgs e) {
      try {
        Reset();
      }
      catch(Exception ex) {
        Logger.Error(typeof(categoryedit).Name + ".btnReset_Click", ex);
        Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    /// <summary>
    /// Handles the Click event of the btnSave control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnSave_Click(object sender, EventArgs e) {
      try {
        Category category;
        int parentId = 0;
        int categoryId = 0;
        int.TryParse(lblCategoryId.Text, out categoryId);
        if(categoryId > 0) {
          category = new Category(categoryId);
        }
        else {
          category = new Category();
        }
        category.Name = txtName.Text.Trim();
        int.TryParse(ddlParentCategory.SelectedValue, out parentId);
        category.ParentId = parentId;
        category.ImageFile = txtImageFile.Text.Trim();
        category.Description = txtDescription.Text.Trim();
        category.Save(WebUtility.GetUserName());
        Reset();
        GetCategoryDataSet();
        LoadTreeView(ds);
        LoadParentCategoryDropDown(ds);
        Master.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblProductCategorySaved"));
      }
      catch(Exception ex) {
        Logger.Error(typeof(categoryedit).Name + ".btnSave_Click", ex);
        Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    #endregion

    #region Methods

    #region Private

    /// <summary>
    /// Gets the category data set.
    /// </summary>
    private void GetCategoryDataSet() {
      ds = new CategoryController().FetchCategoryList();
    }

    /// <summary>
    /// Loads the tree view.
    /// </summary>
    /// <param name="ds">The ds.</param>
    private void LoadTreeView(DataSet ds) {
      tvCategory.Nodes.Clear();
      xmlDataSource.EnableCaching = false;
      xmlDataSource.Data = ds.GetXml();
    }

    /// <summary>
    /// Loads the parent category drop down.
    /// </summary>
    /// <param name="ds">The ds.</param>
    private void LoadParentCategoryDropDown(DataSet ds) {
      ddlParentCategory.Items.Clear();
      DataRow[] rootNodes = ds.Tables["Menu"].Select("ParentId = 0");
      FillNodes(rootNodes, 1);
      ddlParentCategory.Items.Insert(0, new ListItem(LocalizationUtility.GetText("lblRoot"), "0"));
    }

    /// <summary>
    /// Fills the nodes.
    /// </summary>
    /// <param name="nodes">The nodes.</param>
    /// <param name="level">The level.</param>
    private void FillNodes(DataRow[] nodes, int level) {
      DataRow[] childNodes;
      int oldLevel = level;
      string name = string.Empty;
      for(int i = 0; i <= nodes.GetUpperBound(0); i++) {
        for(int j = 0;j < level;j++) {
          name += "-";
        }
        name += nodes[i]["Name"].ToString();
        ddlParentCategory.Items.Add(new ListItem(name, nodes[i]["CategoryId"].ToString()));
        name = string.Empty;
        childNodes = nodes[i].GetChildRows("ParentChild");
        if(childNodes.GetUpperBound(0) >= 0) {
          level = level + 1;
          FillNodes(childNodes, level);
        }
        level = oldLevel;
      }    
    }

    /// <summary>
    /// Resets this instance.
    /// </summary>
    private void Reset() {
      lblCategoryId.Text = string.Empty;
      ddlParentCategory.SelectedIndex = 0;
      txtName.Text = string.Empty;
      txtImageFile.Text = string.Empty;
      txtDescription.Text = string.Empty;
    }

    /// <summary>
    /// Sets the category edit properties.
    /// </summary>
    private void SetCategoryEditProperties() {
      LocalizationUtility.AddLabelText(lblProductCategories);
      LocalizationUtility.AddPanelText(pnlCurrentCategories);
      LocalizationUtility.AddPanelText(pnlEditCategory);
      LocalizationUtility.AddLabelText(lblParentCategory);
      LocalizationUtility.AddLabelText(lblName);
      LocalizationUtility.AddLabelText(lblImageFile);
      LocalizationUtility.AddLabelText(lblDescription);
      LocalizationUtility.AddButtonText(btnSave);
      LocalizationUtility.AddButtonText(btnReset);
      LocalizationUtility.AddButtonText(btnDelete);
      hlImageSelector.NavigateUrl = string.Format("~/admin/imageselector.aspx?view=c&controlId={0}", txtImageFile.ClientID);
      this.Title = LocalizationUtility.GetText("titleProductCategories");
      LocalizationUtility.AddHoverHelp(hlParentCategoryHelp);
      LocalizationUtility.AddHoverHelp(hlCategoryNameHelp);
      LocalizationUtility.AddHoverHelp(hlCategoryImageFileHelp);
      LocalizationUtility.AddHoverHelp(hlCategoryDescriptionHelp);
    }

    #endregion

    #endregion

  }
}
